//
//  OilSlider.swift
//  ruler
//
//  Created by 李帅 on 2018/12/9.
//  Copyright © 2018 李帅. All rights reserved.
//

import UIKit

@IBDesignable

class OilSlider: UIControl {

    @IBInspectable var value: Int = 0 {
        didSet {
            if value != oldValue {
                setNeedsDisplay()
                sendActions(for: .valueChanged)
            }
        }
    }
    
    @IBInspectable var thumbImage: UIImage?
    
    @IBInspectable var maxValue: Int = 10

    @IBInspectable var minValue: Int = 0
    
    @IBInspectable var leftPadding: CGFloat = 0
    
    @IBInspectable var rightPadding: CGFloat = 0
    
    @IBInspectable var scaleLineY: CGFloat = 100
    
    @IBInspectable var longScale: CGFloat = 4
    
    private var scale: CGFloat {
        return (frame.width - leftPadding - rightPadding) / CGFloat(maxValue)
    }
    
    private var beganX: CGFloat = 0
    
    private var beganValue = 0
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        
        beganX = touch.location(in: self).x
        
        beganValue = value
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        
        let x = touch.location(in: self).x
        
        var v = beganValue + Int((x - beganX) / scale)
        
        v = v > maxValue ? maxValue : v
        value = v < minValue ? minValue : v
    }
    
    override func draw(_ rect: CGRect) {
        
        
        let context = UIGraphicsGetCurrentContext()
        
        context?.saveGState()
        
        let left = leftPadding
        let right = rect.width - rightPadding
        
        context?.move(to: CGPoint(x: left, y: scaleLineY))
        context?.addLine(to: CGPoint(x: right, y: scaleLineY))
        
        for x in stride(from: left, through: right, by: scale) {
            context?.move(to: CGPoint(x: x, y: scaleLineY))
            context?.addLine(to: CGPoint(x: x, y: scaleLineY - 7))
        }
        
        for x in stride(from: left, through: right, by: scale * longScale) {
            context?.move(to: CGPoint(x: x, y: scaleLineY))
            context?.addLine(to: CGPoint(x: x, y: scaleLineY - 19))
        }
        
        context?.setLineWidth(1)
        
        if let color = UIColor(hexString: "bebec8") {
            context?.setStrokeColor(color.cgColor)
        }
        
        context?.strokePath()
        
        if let img = thumbImage {
            let x = CGFloat(value) * scale + leftPadding - CGFloat(img.size.width) / 2.0
            
            img.draw(in: CGRect(x: x,
                                y: 14.0,
                                width: CGFloat(img.size.width),
                                height: CGFloat(img.size.height)))
        }
        
        context?.restoreGState()
    }

}
